package com.yuntoyun.codeavatar.app.activity.basic;

import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.google.gson.JsonObject;
import com.yuntoyun.codeavatar.app.R;
import com.yuntoyun.codeavatar.app.activity.main.MainActivity;
import com.yuntoyun.codeavatar.app.fwcore.activity.WebPageActivity;
import com.yuntoyun.codeavatar.app.fwcore.core.AppCoreSign;
import com.yuntoyun.fwcore.appext.data.AppData;
import com.yuntoyun.fwcore.appext.model.UserModel;
import com.yuntoyun.fwcore.base.FwBaseActivity;
import com.yuntoyun.fwcore.model.FwResultJsonDataModel;
import com.yuntoyun.fwcore.model.FwResultJsonListDataModel;
import com.yuntoyun.fwcore.plug.network.retrofit.FwOkHttp;
import com.yuntoyun.fwcore.plug.tool.FwTool;
import com.yuntoyun.fwcore.tool.login.LoginTool;
import com.yuntoyun.fwcore.util.FwIntentUtil;


import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

public class WelcomeActivity extends FwBaseActivity {

    private final int gActionAutoLogin = 901;
    private final int gActionAgreement = 902;
    private final int gActionPrivacy = 903;
    private final int gActionSwitch = 904;

    private String gAgreementUrl, gPrivacyUrl;

    private final String gAgreementText = "请你务必审慎阅读、充分理解“服务协议”和“隐私政策”各条款，包括但不限于：为了向你提供优质信息、内容分享和数据分析等服务，我们需要收集你的设备信息、操作日志等个人信息。你可以在“我的->设置（右上角按扭）->服务协议”中查看、变更、删除个人息并管理你的授权。\n你可阅读《服务协议》和《隐私政策》了解详细信息。如你同意，请点击“同意”并始接受我们的服务。";

    @BindView(R.id.llt_agreement)
    LinearLayout llt_agreement;
    @BindView(R.id.tvw_message)
    TextView tvw_message;

    @Override
    protected void beforeLayout() {

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_basic_welcome;
    }

    @Override
    protected void initView() {
        //开关配置
        this.doSwitchSetting();
    }

    @Override
    protected void initData() {
        boolean isAgreed = AppData.getAppAgreement();
        if (!isAgreed) {
            FwTool.builder().setClickText(tvw_message, gAgreementText,
                    new String[]{"《服务协议》", "《隐私政策》"},
                    new ClickableSpan[]{
                            new ClickableSpan() {
                                @Override
                                public void onClick(@NonNull View widget) {
                                    String str = FwTool.builder().getClickText(widget);
                                    doViewAgreement(str);
                                }
                            },
                            new ClickableSpan() {
                                @Override
                                public void onClick(@NonNull View widget) {
                                    String str = FwTool.builder().getClickText(widget);
                                    doViewAgreement(str);
                                }
                            }
                    });
            llt_agreement.setVisibility(View.VISIBLE);
        } else {
            super.fwHandler.postDelayed(() -> {
                doIntent();
            }, 2000);
        }
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initNavigation() {

    }

    @Override
    protected void messageHandler(Message msg) {

    }

    @Override
    protected void messageHandler(FwResultJsonDataModel model) {
        switch (model.getIndex()) {
            case gActionAutoLogin:
                if (model.getFwData().has("userId") && model.getFwData().has("userToken")) {
                    if (!this.cacheUserInfo(model.getFwData())) {
                        AppData.clearLoginData();
                    }
                } else {
                    AppData.clearLoginData();
                }
                FwIntentUtil.builder().startActivity(this, MainActivity.class);
                finish();
                break;
            case gActionAgreement:
                this.gAgreementUrl = fwGsonUtil.getString(model.getFwData(), "userAgreement");
                doUserAgreement();
                break;
            case gActionPrivacy:
                this.gPrivacyUrl = fwGsonUtil.getString(model.getFwData(), "userAgreement");
                doPrivacyAgreement();
                break;
            case gActionSwitch:
                AppData.setAppTaskSwitch(fwGsonUtil.getInt(model.getFwData(), "taskSwitch"));
                break;
        }
    }

    @Override
    protected void messageHandler(FwResultJsonListDataModel model) {

    }

    @OnClick({R.id.tvw_negative, R.id.tvw_positive})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvw_negative:
                AppData.setAppAgreement(false);
                finish();
                break;
            case R.id.tvw_positive:
                llt_agreement.setVisibility(View.GONE);
                AppData.setAppAgreement(true);
                doIntent();
                break;
        }
    }

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    //协议
    private void doUserAgreement() {
        if (TextUtils.isEmpty(gAgreementUrl)) {
            HashMap<String, Object> map = new HashMap<>();
            AppCoreSign.addSign(map);
            Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getAgreement(map);
            super.doPostData(this.gActionAgreement, observable, true);
        } else {
            Bundle extra = new Bundle();
            extra.putString("ext_title", "用户服务协议");
            extra.putString("ext_url", this.gAgreementUrl);
            FwIntentUtil.builder().startActivity(fwActivity, WebPageActivity.class, extra);
        }
    }

    private void doPrivacyAgreement() {
        if (TextUtils.isEmpty(gPrivacyUrl)) {
            HashMap<String, Object> map = new HashMap<>();
            AppCoreSign.addSign(map);
            Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getPrivacyAgreement(map);
            super.doPostData(this.gActionPrivacy, observable, true);
        } else {
            Bundle extra = new Bundle();
            extra.putString("ext_title", "隐私政策");
            extra.putString("ext_url", this.gPrivacyUrl);
            FwIntentUtil.builder().startActivity(fwActivity, WebPageActivity.class, extra);
        }
    }

    private void doViewAgreement(String clickStr) {
        if (clickStr.indexOf("服务协议") != -1) {
            doUserAgreement();
        } else if (clickStr.indexOf("隐私政策") != -1) {
            doPrivacyAgreement();
        }
    }

    ////////

    //缓存数据
    private boolean cacheUserInfo(JsonObject joData) {
        if (null == joData)
            return false;

        UserModel model = new UserModel();
        model.setUserId(fwGsonUtil.getInt(joData, "userId"));
        model.setUserToken(fwGsonUtil.getString(joData, "userToken"));
        if (AppData.setPostData(model)) {
            //合伙人身份：0 不是；1 普通合伙人；2 商家合伙人；3 普通合伙人-已冻结-已到期；4 商家合伙人-已冻结-已到期
            model.setUserAuth(fwGsonUtil.getInt(joData, "is_partner"));
            return AppData.setUserData(model);
        }
        return false;
    }

    //加载开关设置
    private void doSwitchSetting() {
        HashMap<String, Object> map = new HashMap<>();
        AppCoreSign.addSign(map);
        Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getSwitchSetting(map);
        super.doPostData(this.gActionSwitch, observable, false);
    }

    //跳转界面
    private void doIntent() {
        if (LoginTool.isLogin()) {
            //自动登录
            HashMap<String, Object> map = new HashMap<>();
            AppCoreSign.addSign(map);
            Observable<FwResultJsonDataModel> observable =
                    FwOkHttp.getFwAPIService().getAutoLogin(map);
            //加载框，受当前Activity主题影响，显示启动页背景，所以不显示加载框。
            super.doPostData(this.gActionAutoLogin, observable, false);
        } else {
            FwIntentUtil.builder().startActivity(fwActivity, MainActivity.class);
            finish();
        }
    }

}
